#include "timer.h"
#include <stdio.h>
#include <stdlib.h>

// 定时器回调函数在以下位置添加：
void timer_callback(uv_timer_t* handle) {
    system("/home/meetyoo/device_inspect/script");
}

// 定时器列表结构体
typedef struct timer_list_t {
    unsigned int timeout;   // 定时器第一次调用的等待时间(ms)
    int repeat_time;        // 定时器回调函数重复调用间隔(ms)
    uv_timer_cb timer_func; // 定时器回调函数
    uv_timer_t *timer_p;    // 定时器指针
} timer_list_t;

// 定时器列表
static timer_list_t s_timer_list[] = {
    //定时器回调函数设置在以下位置添加：
    {0, 5000, timer_callback, NULL}, 
    {0, 0, NULL, NULL} // 结束标志
};

// 循环初始化定时器
int init_timer(uv_loop_t* loop) {
    timer_list_t *timer_list = s_timer_list;
    for (; timer_list->timer_func; timer_list++) {
        if (timer_list->timer_p != NULL) {
            continue;
        }
        timer_list->timer_p = (uv_timer_t*) malloc(sizeof(uv_timer_t));
        if (uv_timer_init(loop, timer_list->timer_p) != 0) {
            return -1;
        }
        if (uv_timer_start(timer_list->timer_p, timer_list->timer_func, timer_list->timeout, timer_list->repeat_time) != 0) {
            return -1;
        }
    }
    return 0;
}

void uninit_timer() {
    timer_list_t *timer_list = s_timer_list;
    for (; timer_list->timer_func; timer_list++) {
        if (timer_list->timer_p == NULL) {
            continue;
        }
        uv_timer_stop(timer_list->timer_p);
        free(timer_list->timer_p);
        timer_list->timer_p = NULL;
    }
}